package communication

import (
	"context"
	"fmt"
	"math/rand"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/redis/go-redis/v9"
)

// SmsUtil 短信工具
type SmsUtil struct {
	redis *redis.Client
}

// NewSmsUtil 创建短信工具实例
func NewSmsUtil() (*SmsUtil, error) {
	return &SmsUtil{
		redis: database.RedisClient,
	}, nil
}

// generateVerificationCode 生成6位数字验证码
func (s *SmsUtil) generateVerificationCode() string {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	return fmt.Sprintf("%06d", r.Intn(1000000))
}

// SendVerificationCode 发送短信验证码
func (s *SmsUtil) SendVerificationCode(phone, purpose string) error {
	// 生成验证码
	code := s.generateVerificationCode()

	// 创建阿里云短信客户端
	client, err := dysmsapi.NewClientWithAccessKey(
		"cn-hangzhou", // 默认区域
		"LTAI5tMWCY85XndnwY6DAXXa",
		"8XfFjLv7YftY4LHTz1KCtadKEtpFbL",
	)
	if err != nil {
		return fmt.Errorf("创建短信客户端失败: %v", err)
	}

	// 创建发送短信请求
	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"
	request.PhoneNumbers = phone
	request.SignName = "湖南蓝博品牌营销策划"
	request.TemplateCode = "SMS_485340449"
	request.TemplateParam = fmt.Sprintf(`{"code":"%s"}`, code)

	// 发送短信
	response, err := client.SendSms(request)
	if err != nil {
		return fmt.Errorf("发送短信失败: %v", err)
	}

	// 检查发送结果
	if response.Code != "OK" {
		return fmt.Errorf("发送短信失败: %s", response.Message)
	}

	// 将验证码保存到Redis，设置5分钟过期
	ctx := context.Background()
	key := fmt.Sprintf("sms:verification:%s:%s", purpose, phone)
	err = s.redis.Set(ctx, key, code, 5*time.Minute).Err()
	if err != nil {
		return fmt.Errorf("保存验证码失败: %v", err)
	}

	return nil
}

// VerifyCode 验证短信验证码
func (s *SmsUtil) VerifyCode(phone, code, purpose string) (bool, error) {
	ctx := context.Background()
	key := fmt.Sprintf("sms:verification:%s:%s", purpose, phone)

	// 从Redis获取验证码
	savedCode, err := s.redis.Get(ctx, key).Result()
	if err == redis.Nil {
		return false, fmt.Errorf("verification_code_expired")
	} else if err != nil {
		return false, fmt.Errorf("get_verification_code_failed: %v", err)
	}

	// 验证码比对
	if savedCode != code {
		return false, fmt.Errorf("invalid_verification_code")
	}

	// 验证成功后删除验证码
	err = s.redis.Del(ctx, key).Err()
	if err != nil {
		return false, fmt.Errorf("delete_verification_code_failed: %v", err)
	}

	return true, nil
}

// SendForgotPasswordCode 发送忘记密码验证码
func (s *SmsUtil) SendForgotPasswordCode(phone string) error {
	return s.SendVerificationCode(phone, "forgot_password")
}
